/*
 * @Author: Cxy
 * @Date: 2021-05-22 19:27:50
 * @LastEditors: Cxy
 * @LastEditTime: 2022-10-11 15:42:08
 * @FilePath: /daimler-transport-admind:/giteeBlog/blogServe/socket/until.js
 */
/**
 * @description: 多点登录账户修改及在线人员查找
 * @param {*} data  admin_Code  账户名  login_Device  登录设备类型
 * @param {*} socket  socket对象
 * @param {*} loginSingOut  true 登陆状态, false 登出状态
 */
const { find, findCount, updateMany } = require('../mongo/db')
const update_Find_Online = async (data, socket, loginSingOut = true) => {
  const { admin_Code, login_Device } = data
  if (loginSingOut) {
    await updateMany('users', { admin_Code }, { socket_Id: socket.id, online_Offline: 1, login_Device })
  } else {
    /**
     * @description: admin_Code
     * @params 有值：固定用户下线
     * @params 无值：固定socket_Id下线
     */
    const condi_Param = admin_Code ? { admin_Code } : { socket_Id: socket.id }
    await updateMany('users', condi_Param, { socket_Id: '', online_Offline: 0, login_Device: '' })
  }
  // 获取登陆人员信息
  const Login_Users = await find('users', { online_Offline: 1 }, {}, { _id: 0, admin_Code: 1, role_Name: 1, nick_Name: 1, login_Device: 1, created_At: 1, head_Portrait: 1 })
  // 获取文章数量信息
  const article_Totle = await findCount('article', {})
  const article_Totle_Arrangement = article_Totle.countNum
  // 获取网站访问量信息
  const Views_Totle = await find('views', {}, {}, { count_Num: 1 })
  const Views_Totle_Arrangement = Views_Totle.data[0].count_Num
  arrange_Data = [{ countNum: Login_Users.data.length, Login_Users_Arrangement: Login_Users.data, code: 'ON_LINE' }, { countNum: article_Totle_Arrangement, code: 'ARTICLE_COUNT' }, { countNum: Views_Totle_Arrangement, code: 'VISITS' }]
  socket.emit('Login_Users', { data: arrange_Data })
  socket.to('rootRoom').emit('Login_Users', { data: arrange_Data })
}

/**
 * @description: 延迟通知，客户端规定时间重连不通知其他用户
 * @param {*} socket socket实例
 */
const reconne_Specified_Time = async (socket) => {
  let timer = setTimeout(async () => {
    // 根据socketId改变，判断客户端刷新
    const { data } = await find('users', { socket_Id: socket.id }, {}, { updated_At: 1 })
    if (data[0]) {
      // 客户端断开连接时，根据当前客户端已存socketID初始化登录信息
      update_Find_Online({}, socket, false)
    }
    clearTimeout(timer)
    timer = null
  }, 5000);
}
module.exports = { update_Find_Online, reconne_Specified_Time }

// socket.emit() ：向建立该连接的客户端广播
// socket.broadcast.emit() ：向除去建立该连接的客户端的所有客户端广播
// io.sockets.emit() ：向所有客户端广播，等同于上面两个的和